import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

const dataDir = path.join(__dirname, '..', 'data');

function readJSONFile(filename) {
    const filePath = path.join(dataDir, filename);
    try {
        const content = fs.readFileSync(filePath, 'utf8');
        return JSON.parse(content);
    } catch (error) {
        console.error(`读取文件失败 ${filename}:`, error);
        return [];
    }
}

async function testPermissions() {
    console.log('=== 测试权限分配和检查 ===\n');

    // 读取数据
    const roles = readJSONFile('roles.json');
    const permissions = readJSONFile('permissions.json');
    const rolePermissions = readJSONFile('rolePermissions.json');
    const userRoles = readJSONFile('userRoles.json');
    const users = readJSONFile('users.json');

    console.log('角色列表:');
    roles.forEach(role => {
        console.log(`  ${role.name} (id: ${role.id}, code: ${role.code})`);
    });

    console.log('\n权限列表:');
    permissions.forEach(perm => {
        console.log(`  ${perm.name} (id: ${perm.id}, code: ${perm.code})`);
    });

    console.log('\n角色-权限关联:');
    roles.forEach(role => {
        const rps = rolePermissions.filter(rp => rp.roleId === role.id);
        const permIds = rps.map(rp => rp.permissionId);
        const perms = permissions.filter(p => permIds.includes(p.id));
        console.log(`\n${role.name} (roleId: ${role.id}):`);
        if (perms.length === 0) {
            console.log('  无权限');
        } else {
            perms.forEach(perm => {
                console.log(`    ✓ ${perm.name} (${perm.code})`);
            });
        }
    });

    console.log('\n用户-角色关联:');
    users.forEach(user => {
        const urs = userRoles.filter(ur => ur.userId === user.id);
        const roleIds = urs.map(ur => ur.roleId);
        const userRoles_ = roles.filter(r => roleIds.includes(r.id));
        console.log(`\n${user.username} (userId: ${user.id}):`);
        userRoles_.forEach(role => {
            console.log(`  - ${role.name} (${role.code})`);
            // 获取该角色的权限
            const rps = rolePermissions.filter(rp => rp.roleId === role.id);
            const permIds = rps.map(rp => rp.permissionId);
            const perms = permissions.filter(p => permIds.includes(p.id));
            console.log(`    拥有权限: ${perms.length} 个`);
            perms.forEach(perm => {
                console.log(`      • ${perm.code}`);
            });
        });
    });

    // 测试特定权限检查
    console.log('\n\n=== 测试教师权限 ===');
    const teacherRoleId = roles.find(r => r.code === 'teacher')?.id;
    const teacherUserIds = userRoles.filter(ur => ur.roleId === teacherRoleId).map(ur => ur.userId);

    teacherUserIds.forEach(userId => {
        const user = users.find(u => u.id === userId);
        if (user) {
            console.log(`\n教师: ${user.username} (userId: ${user.id})`);
            const rps = rolePermissions.filter(rp => {
                const ur = userRoles.find(u => u.userId === userId);
                return ur && rp.roleId === ur.roleId;
            });
            const permIds = [...new Set(rps.map(rp => rp.permissionId))];
            const perms = permissions.filter(p => permIds.includes(p.id));

            // 检查特定权限
            const testPermissions = ['student:create', 'student:update', 'student:delete'];
            testPermissions.forEach(permCode => {
                const perm = permissions.find(p => p.code === permCode);
                const hasPerm = perm && permIds.includes(perm.id);
                console.log(`  ${permCode}: ${hasPerm ? '✓ 有权限' : '✗ 无权限'}`);
            });
        }
    });
}

testPermissions().catch(console.error);

